﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using Zhaoxi.Communication.Base;
using Zhaoxi.Configuration.Base;

namespace Zhaoxi.Communication.Protocols
{
    public class ModbusTCP : CommBase
    {
        Modbus.Device.ModbusIpMaster ipMaster;
        byte SlaveId = 1;

        public override void Connect(params CommParamEntity[] args)
        {
            string ip = "127.0.0.1";
            var p_ip = args.Where(p => p.name == "IP")
                .FirstOrDefault();
            if (p_ip != null) ip = p_ip.value;

            string port = "502";
            var p_port = args.Where(p => p.name == "Port")
                .FirstOrDefault();
            if (p_port != null) port = p_port.value;


            var p_slave = args.Where(p => p.name == "SlaveId")
                .FirstOrDefault();
            if (p_slave != null) SlaveId = byte.Parse(p_slave.value);


            TcpClient tcpClient = new TcpClient();
            tcpClient.Connect(ip, int.Parse(port));
            ipMaster = Modbus.Device.ModbusIpMaster.CreateIp(tcpClient);
        }

        public override void StartRead(params VariableEntity[] variables)
        {
            foreach (var item in variables)
            {
                // 这里面涉及到Modbus相关的概念信息，自行了解，找助教老师拿下资料
                ushort[] values = ipMaster.ReadHoldingRegisters(
                      SlaveId,
                      (ushort)(ushort.Parse(item.address) - 40001),
                      1);

                item.Value = values[0];
            }
        }
    }
}
